import freemarker.template.TemplateException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.wcf.util.freeMarker.FreemarkerUtil;

import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by wuchaofei on 2016/3/15.
 */
public class Main {

    private static final String FUNCION_REG = "";//PHP function 正则表达式
    private static FilenameFilter phpFileFilter;

    public static void main(String[] args) throws IOException, TemplateException {

//        String s="id,parent_id,name,description,logo,extra_info,seo_title,seo_keywords,seo_description";
//        splitToProperty(s);
//        s="get_properties_by_group_ids";
//        splitAndUpperFirst(s);

//        vonvertPhpModelToJava("D:\\le\\workspace\\php_lemall\\usa_wap\\trunk\\application\\models\\Product.php");
//        phpFunctions("D:\\le\\workspace\\php_lemall\\usa_wap\\trunk\\application\\models\\Product.php");
//        replaceTxt(null,null);


//        phpToFtl("E:\\le\\us_m_lemall\\src\\main\\webapp\\WEB-INF\\ftl\\en_US\\common\\header.ftl","E:\\le\\us_m_lemall\\src\\main\\webapp\\WEB-INF\\ftl\\en_US\\common\\header.gen.ftl");
//        phpConfigToFtl("D:\\le\\workspace\\php_lemall\\usa_wap\\trunk\\application\\config\\api_url.php","E:\\le\\us_m_lemall\\src\\main\\webapp\\WEB-INF\\ftl\\en_US\\common\\js_api.gen.ftl");

//        phpToFtl("D:\\le\\workspace\\php_lemall\\usa_wap\\trunk\\application\\views\\comm\\footer.php","E:\\le\\us_m_lemall\\src\\main\\webapp\\WEB-INF\\ftl\\en_US\\common\\footer.ftl");
//          commentSplit("E:\\le\\us_m_lemall\\src\\main\\webapp\\WEB-INF\\ftl\\en_US\\common\\js_api.ftl", "E:\\le\\us_m_lemall\\src\\main\\webapp\\WEB-INF\\ftl\\en_US\\common\\js_api.gen.ftl");

//        phpToFtl("E:\\le\\us_m_lemall\\src\\main\\webapp\\WEB-INF\\ftl\\en_US\\products\\_script.php","E:\\le\\us_m_lemall\\src\\main\\webapp\\WEB-INF\\ftl\\en_US\\products\\_script.ftl");
//        phpToFtl("E:\\le\\us_m_lemall\\src\\main\\webapp\\WEB-INF\\ftl\\en_US\\products\\category.php","E:\\le\\us_m_lemall\\src\\main\\webapp\\WEB-INF\\ftl\\en_US\\products\\category.ftl");
//        phpToFtl("E:\\le\\us_m_lemall\\src\\main\\webapp\\WEB-INF\\ftl\\en_US\\products\\comments.php","E:\\le\\us_m_lemall\\src\\main\\webapp\\WEB-INF\\ftl\\en_US\\products\\comments.ftl");
//        phpToFtl("E:\\le\\us_m_lemall\\src\\main\\webapp\\WEB-INF\\ftl\\en_US\\products\\list.php","E:\\le\\us_m_lemall\\src\\main\\webapp\\WEB-INF\\ftl\\en_US\\products\\list.ftl");
//        phpToFtl("E:\\le\\us_m_lemall\\src\\main\\webapp\\WEB-INF\\ftl\\en_US\\products\\view.php","E:\\le\\us_m_lemall\\src\\main\\webapp\\WEB-INF\\ftl\\en_US\\products\\view.ftl");


//        <?php foreach ($categories as $key => $category): ?>
//        boolean f=testReg("<?php foreach ($categories as $key => $category): ?>", "<\\?php\\s{1,}foreach\\s{1,}\\(\\$([a-zA-Z0-9]+)\\s+as\\s+\\$([a-zA-Z0-9]+)\\s+\\=\\>\\s+\\$([a-zA-Z0-9]+)\\):\\s{0,}\\?>");
//        System.out.println(f);

//         phpToFtl("D:\\le\\workspace\\php_lemall\\usa_wap\\trunk\\application\\views\\lemas\\products.php","E:\\le\\us_m_lemall\\src\\main\\webapp\\WEB-INF\\ftl\\en_US\\lemas\\products.ftl");

//        List fileList = new ArrayList();
//        walkFolder(getPhpFileFilter(), "D:\\le\\workspace\\php_lemall\\usa_wap\\trunk\\application", fileList);
//        System.out.println(fileList);
//        walkerReplace("D:\\le\\workspace\\php_lemall\\usa_wap\\trunk\\application\\views\\users","E:\\le\\us_m_lemall\\src\\main\\webapp\\WEB-INF\\ftl\\en_US\\users");
//        walkerReplace("D:\\le\\workspace\\php_lemall\\usa_wap\\trunk\\application\\views\\address","out\\address");
//        vonvertPhpControllerToJava("D:\\le\\workspace\\php_lemall\\usa_wap\\trunk\\application\\controllers\\Products.php");
        //生成控制器
//        genJavaController("D:\\le\\workspace\\php_lemall\\usa_wap\\trunk\\application\\controllers","out\\controllers",".java");
        walkerReplace("D:\\le\\workspace\\php_lemall\\usa_wap\\trunk\\application\\views\\orders","out\\orders");
    }

    /**
     * 根据php文件自动生成java controller
     * @param fromDir php控制器文件位置
     * @param toDir java 控制器文件位置
     */
    public static void genJavaController(String fromDir, String toDir,String suffix) throws IOException, TemplateException {
        if(toDir.endsWith("/") || toDir.endsWith("\\")){
            toDir = toDir.substring(0,toDir.length()-1);
        }

        File fromRootFile = new File(fromDir);
        String fromRootPath=fromRootFile.getAbsolutePath();
        Collection<File> fileList = FileUtils.listFiles(fromRootFile, new String[]{"php"}, true);
        for (File file : fileList) {
            String toName = file.getName().split("\\.")[0]+"Controller"+suffix;
            String parentPath = file.getParentFile().getAbsolutePath();
            File toFile = new File(parentPath.replace(fromRootPath, toDir), toName);
//            封装数据
            Map<String,Object> map=new HashMap<String,Object>();
            collectPhpControllerActions(file.getPath(),map);
            System.out.println(map);
            FreemarkerUtil.genController((String)map.get("className"),toFile.getPath(),map);
        }
    }

    /**
     * 读取文件夹
     * @param fromDir 来源文件夹
     * @param toDir 目标文件夹
     * @return
     */
    public static void walkerReplace(String fromDir,String toDir){
        if(toDir.endsWith("/") || toDir.endsWith("\\")){
            toDir = toDir.substring(0,toDir.length()-1);
        }

        File toDirFile = new File(toDir);
        if(!toDirFile.exists()){
            toDirFile.mkdirs();
        }
        toDirFile=null;

        File fromRootFile = new File(fromDir);
        String fromRootPath=fromRootFile.getAbsolutePath();
        Collection<File> fileList = FileUtils.listFiles(fromRootFile, new String[]{"php"}, true);
        for (File file : fileList) {
            String toName = file.getName().split("\\.")[0]+".ftl";
            String parentPath = file.getParentFile().getAbsolutePath();
            File toFile = new File(parentPath.replace(fromRootPath, toDir), toName);
            phpToFtl(file.getPath(),toFile.getPath());
        }
    }

    /**
     * 递归遍历文件夹下所有的文件
     * @param path
     * @param fileList
     */
    public static void walkFolder(FilenameFilter filter,String path,List fileList) {
        if(fileList==null){
            fileList=new ArrayList();
        }
        File file = new File(path);
        if (file.exists()) {
            File[] files = file.listFiles();
            if (files.length == 0) {
                System.out.println("文件夹是空的!");
                return;
            } else {
                for (File file2 : files) {
                    if (file2.isDirectory()) {
//                        System.out.println("文件夹:" + file2.getAbsolutePath());
                        walkFolder(filter,file2.getAbsolutePath(),fileList);
                    } else {
                        //文件接口
                        fileList.add(file2.getAbsolutePath());
//                        System.out.println("文件:" + file2.getAbsolutePath());
                    }
                }
            }
        } else {
            System.out.println("文件不存在!");
        }
    }

    /**
     * 将ftl文件中json中的注释分离出来
     * @param from
     * @param to
     */
    private static void commentSplit(String from, String to) {
        Map<String, String> map=new HashMap<String, String>();
        map.put("([\\,\\s]+)(<#--.+-->)","$1\"$2\\+\"");
        replaceContent(from, to, map);
    }

    /**
     * php配置文件转换成ftl中js对象
     * @param from
     * @param to
     */
    private static void phpConfigToFtl(String from, String to) {
        Map<String, String> map=new HashMap<String, String>();
        map.put("<\\?php","");
        map.put("\\$config\\s+\\[\'api_url\'\\] = array \\(","<#assign jsapiStr = \"\n" +
                "{\"+");
//        map.put("\\);","\"};\">");
        map.put("\\);","\"\\};\">");
        map.put("=>",":");
//        map.put("//old","<#--old-->");
        map.put("([\\s\\,]{1,})//(.{1,})","$1<#--$2-->");
        replaceContent(from, to, map);
        map.clear();
        map.put("'","\\\\"+"\"");
        replaceContent(to, to+".ftl", map);
    }

    public static String splitAndUpperFirst(String s){
        String[] arr = s.split("_");
        StringBuffer sb=new StringBuffer();
        for (int i = 0; i < arr.length; i++) {
            if(i!=0){
                sb.append(arr[i].substring(0,1).toUpperCase()).append(arr[i].substring(1));
            }else{
                sb.append(arr[i].substring(0,1)).append(arr[i].substring(1));
            }
        }
        System.out.println(sb.toString());
        return sb.toString();
    }

    public static void splitToProperty(String s){
        String[] arr = s.split(",");
        for (String s1 : arr) {
            System.out.println("private String "+s1+";");
        }
    }

    /**
     * 提取php controller中的action及controller名字
     * @param path php文件路径
     * @param map 数据
     * @throws IOException
     */
    public static void collectPhpControllerActions(String path,Map<String,Object> map) throws IOException {
        List<String> actions =new ArrayList<String>();
        FileReader reader = new FileReader(path);
        BufferedReader br = new BufferedReader(reader);
        String str = null;
        String className= getCLassName(path);
        map.put("className",className);

        StringBuffer sb=new StringBuffer();
        while((str = br.readLine()) != null) {
            if(str.contains("function")){
                String action = getActionName(str);
                if(action!=null){
                    actions.add(action);
                }
            }
        }
        map.put("actions",actions);
        br.close();
        reader.close();
    }


    public static void vonvertPhpControllerToJava(String path) throws IOException {
        List<String> funNameList =new ArrayList<String>();
        FileReader reader = new FileReader(path);
        BufferedReader br = new BufferedReader(reader);
        String str = null;

        String controller= getCLassName(path);
        String action=null;

        StringBuffer sb=new StringBuffer();
        while((str = br.readLine()) != null) {
            action = getActionName(str);
            if(action!=null){
                sb.append("@RequestMapping(value = \"").append(action).append("\")\r\n");
                sb.append("public String ").append(action).append("(HttpServletRequest request, ModelMap model){\r\n");
                sb.append("");
                sb.append("    return \"").append(controller).append("/").append(action).append("\";\r\n");
                sb.append("}\r\n");
            }
        }

        System.out.println(sb.toString());
        br.close();
        reader.close();
    }

    public static void vonvertPhpModelToJava(String path) throws IOException {
        List<String> funNameList =new ArrayList<String>();
        FileReader reader = new FileReader(path);
        BufferedReader br = new BufferedReader(reader);
        String str = null;

//        String controller=getCLassName(path);
        String model=null;
        StringBuffer sb=new StringBuffer();
        while((str = br.readLine()) != null) {
            model = getDaoName(str);
            if(model!=null){
//                <select id="getProductsByGroupIds"  parameterType="java.util.Map" resultMap="ProductResultMap">

                sb.append("<select id=\"").append(splitAndUpperFirst(model)).append("\"  parameterType=\"java.util.Map\" resultMap=\"\">\r\n");
                sb.append("</select>\r\n");
            }
        }

        System.out.println(sb.toString());
        br.close();
        reader.close();
    }

    /**
     * 获取action name
     * @param line
     * @return
     */
    public static String getActionName(String line) {
//        function get_product_by_pid( $pid = "" ){
        return getLineFunctionName(line,"(public)?\\s{0,}function\\s+([a-zA-Z0-9_]+)\\s{0,}\\(.{0,}\\)\\s{0,}\\{?",2);
    }

    public static String getSelect(String line){
//        $this->db->select('pid,title,subtitle,group_id,property_ids,extra_info,seo_title,seo_keywords,seo_description,category_id,is_can_buy,url,extra_info,product_ext');
        if(line.contains("select")){
            int start=line.indexOf("('")+2;
            int end = line.indexOf("')")-1;
            return line.substring(start,end);
        }
        return null;
    }
    public static String getFrom(String line){
//        $this->db->from('articles');
        if(line.contains("from")){
            int start=line.indexOf("('")+2;
            int end = line.indexOf("')")-1;
            return line.substring(start,end);
        }
        return null;
    }

    public static Map getWhere(String line){
//        $this->db->where('pid',$pid);
        Map<String, String> map = new HashMap<String, String>();
        if(line.contains("where") && !line.contains("where_in")){
            int start=line.indexOf("(");
            int end = line.lastIndexOf(")");
            String keyValue=line.substring(start, end);
            keyValue=keyValue.replaceAll("[\'\"\\(\\)]","");
            String[] arr = keyValue.split(",");
            map.put(arr[0],arr[1]);
            return map;
        }
        return null;
    }
    public static Map getWhereIn(String line){
//        $this->db->where('pid',$pid);
        Map<String, String> map = new HashMap<String, String>();
        if(line.contains("where_in")){
            int start=line.indexOf("(");
            int end = line.lastIndexOf(")");
            String keyValue=line.substring(start, end);
            keyValue=keyValue.replaceAll("[\'\"\\(\\)]","");
            String[] arr = keyValue.split(",");
            map.put(arr[0],arr[1]);
            return map;
        }
        return null;
    }
    public static Map<String, String> getOrderBy(String line){
//        $this->db->order_by('sorts','ASC');
        Map<String, String> map = new HashMap<String, String>();
        if(line.contains("order_by")){
            int start=line.indexOf("(")+1;
            int end = line.lastIndexOf(")")-1;
//            $this->db->order_by($order,$sort);
            line=line.substring(start,end).replaceAll("'","").replaceAll("\"","");
            String[] arr = line.split(",");
            map.put(arr[0], arr[1]);
            return map;
        }
        return null;
    }

    public static String getLimit(String line){
//        $this->db->limit(1);
        if(line.contains("limit")){
            int start=line.indexOf("(")+1;
            int end=line.lastIndexOf(")")-1;
            return line.substring(start,end);
        }
        return null;
    }




    /**
     * 匹配dao中function name
     * @param line
     * @return
     */
    public static String getDaoName(String line){
        return getLineFunctionName(line,"^function(\\W+)([a-zA-Z0-9_\\w]*)\\(.{0,}\\)\\{$",2);
    }

    public static String getLineFunctionName(String line,String regex,int group){
        line=line.trim();
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(line);

        if(matcher.matches()) {
            String str = matcher.group(group);
            return str.startsWith("_")?null:str;
        }
        return null;
    }

    /**
     * 根据文件全路径，取文件名拼类名，控制器名
     * @param path
     * @return
     */
    public static String getCLassName(String path){
        File f=new File(path);
        String name = f.getName();
        String[] arr = name.split("\\.");
        return arr[0].toLowerCase();
    }

    /**
     * php文件替换为freemarker文件
     * @param from
     * @param to
     */
    public static void phpToFtl(String from,String to){
        Map<String, String> map = new TreeMap<String,String>();
        map.put("<\\?php\\s{1,}echo\\s{1,}media\\('([a-zA-Z0-9_\\.\\/]+)'\\)\\s{0,};\\s{0,}\\?>","\\${rootResourcePath}/$1");
        map.put("<\\?=media\\('([a-zA-Z0-9_\\.\\/]+)'\\)\\s{0,};{0,}\\s{0,}\\?>","\\${rootResourcePath}/$1");
        map.put("<\\?php\\s{1,}echo\\s{1,}site_url\\('([a-zA-Z0-9\\.\\/_]+)'\\)\\s{0,};{0,}\\s{0,}\\?>","\\${rootPath}/$1.html");
        map.put("<\\?php\\s{1,}echo\\s{1,}site_url\\(\\)\\s{0,};{0,}\\s{0,}\\?>","\\${rootPath}");
//        <?php echo json_encode($api_url);?>
        map.put("<\\?php\\s{1,}echo\\s{1,}json_encode\\(\\$api_url\\)\\s{0,};\\s{0,}\\?>","\\$\\{jsapiStr\\?replace\\(\"\\\\r\\\\n\", \"\")\\?replace\\(\" \", \"\"\\)\\}");
//        <?php if($headerTemp == 1):?>
//        map.put("<\\?php\\s{1,}if\\(\\$([a-zA-Z0-9]+)\\s{0,}([=><]{1,})\\s{0,}([a-zA-Z0-9]+)\\s{0,}\\)\\s{0,};\\s{0,}\\?>","<#if $1$2$3>");
        map.put("<\\?php\\s+if\\(\\$([a-zA-Z0-9]+)\\s{0,}([><=]+)\\s{0,}([a-zA-Z0-9]+)\\):\\?\\>","<#if $1$2$3>");
//        <?php elseif($headerTemp  == 2): ?>
        map.put("<\\?php\\s+elseif\\(\\$([a-zA-Z0-9]+)\\s{0,}([><=]+)\\s{0,}([a-zA-Z0-9]+)\\)\\s{0,}:\\s{0,}\\?\\>","<#elseif $1$2$3>");
//        <?php  else:?>
        map.put("<\\?php\\s+else\\s{0,}:\\s{0,}\\?\\>","<#else>");
//        <?php endif;?>
//        map.put("<\\?php\\s+endif\\s{0,}:\\s{0,}\\?\\>","</#if>");
        map.put("<\\?php\\s+endif\\s{0,};\\s{0,}\\?>","</#if>");
//        'pageTitle' => "LeTV, Earphone, Bluetooth Speaker/Headphone",
        map.put("\\s+\'(.+)\'\\s{0,}=>\\s{0,}[\"\']{1}(.+)[\"\']{1}[\\,]{0,}","<#assign $1 = \"$2\">");
//        <?php foreach ($categories as $key => $category): ?>
//        map.put("<\\?php\\s{1,}foreach\\s{1,}\\($([a-zA-Z0-9]{1,})\\s{1,}as\\s{1,}$([a-zA-Z0-9]{1,})\\s{1,}=>\\s{1,}$([a-zA-Z0-9]{1,})\\)\\s{0,}:\\s{0,}\\?>","<#list $1 as $2>");
        map.put("<\\?php\\s{1,}foreach\\s{1,}\\(\\$([a-zA-Z0-9]+)\\s+as\\s+\\$([a-zA-Z0-9]+)\\s+\\=\\>\\s+\\$([a-zA-Z0-9]+)\\):\\s{0,}\\?>","<#list $1 as $3>");
//        <?php endforeach; ?>
        map.put("<\\?php\\s+endforeach;\\s+\\?>","</#list>");
//        <?php echo $category['link']; ?>
        map.put("<\\?php\\s+echo\\s+\\$([a-zA-Z0-9]+)\\[\\'([a-zA-Z0-9]+)\\'\\];\\s+\\?>","\\${$1.$2!}");
//        <?php echo get_upload_url($category['logo']); ?>
        map.put("<\\?php\\s+echo\\s+get_upload_url\\(\\$([a-zA-Z0-9]+)\\[\\'([a-zA-Z0-9]+)\\'\\]\\);\\s+\\?>", "\\${get_upload_url($1.$2)}");
//        <?php echo get_upload_url('/'); ?>
        map.put("<\\?php\\s+echo\\s+get_upload_url\\(\\'/\\'\\);?\\s+\\?>", "\\${get_upload_url('/')}");
//        <?php  if($key == (count($categories) -1) ) :?>
        map.put("<\\?php\\s+if\\(\\$([a-zA-Z0-9]+)\\s+==\\s+\\(count\\(\\$([a-zA-Z0-9]+)\\)\\s{0,}([\\+\\-\\*\\/]+)([0-9]+)\\)\\s{0,}\\)\\s{0,}:\\s{0,}\\?>", "<#if __$2_$1==$2?size$3$4>");
//        <?php load_view('products/_script');?>
        map.put("<\\?php\\s+load_view\\(\\'([a-zA-Z0-9\\/_]+)\\'\\);?\\s{0,}\\?>", "<#include \"$1.ftl\" />");
//        <?php load_view('comm/header',array('pageTitle'=>"My cart"))?>
        map.put("<\\?php\\s+load\\_view\\(\\'([a-zA-Z0-9\\/_]+)\\'\\,\\s{0,}array\\(\\'([a-zA-Z0-9\\/_]+)\\'\\s{0,}=>\\s{0,}\"(.+)\"\\)\\)\\s{0,}\\?>", "<#include \"$1.ftl\" />\n<#assign $2=\"$3\" />");
//        <?php load_view('comm/header'
        map.put("<\\?php\\s+load_view\\(\\'comm/header\\'", "<#include \"../common/header.ftl\" />");
//        'pageTitle'=>"Purchase channels of Le code--LeMall-LeMall",'headerTitle'=>'Purchase channels of Le code--LeMall-LeMall'
        map.put("\\'pageTitle'=>[\"\\']+([^\'\"]+)[\"\\']?", "\n<#assign pageTitle=\"$1\" />");
        map.put("\\'headerTitle'=>[\"\\']+([^\'\"]+)[\"\\']?", "\n<#assign headerTitle=\"$1\" />");
//        '<?php echo $lema?>';
//        <?php echo $order_id; ?>
        map.put("<\\?php\\s+echo\\s+\\$([a-zA-Z0-9_]+);\\s{0,}?\\s{0,}\\?>", "\\${$1!}");
        replaceContent(from, to, map);
    }

    public static void replaceContent(String filePath, String savePath,Map<String,String> map) {
        BufferedReader br = null;
        BufferedWriter bw = null;
        String content = "";


        try {
            br = new BufferedReader(new FileReader(filePath));
            bw = new BufferedWriter(new FileWriter(savePath));
            String line="";
            String sep = System.getProperty("line.separator");

            while(line!=null) {
                line = br.readLine();
                if(null!=line){
                    //处理循环中的$key
                    if(line.contains("foreach") && line.contains("=>")){
                        //提取循环中的索引
                        putForeachKeyToMap(line, map);
                    }
                    line = replaceTxt(line,map);
                    bw.write(line +sep);
                }
            }
            bw.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(br != null) br.close();
                if(bw != null) bw.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 正则表达式提取
     * php循环中的索引
     * @param line
     * @param map
     */
    public static void putForeachKeyToMap(String line, Map<String, String> map) {
        Pattern p=Pattern.compile("<\\?php\\s{1,}foreach\\s{1,}\\(\\$([a-zA-Z0-9]+)\\s+as\\s+\\$([a-zA-Z0-9]+)\\s+\\=\\>\\s+\\$([a-zA-Z0-9]+)\\):\\s{0,}\\?>");
        Matcher matcher=p.matcher(line.trim());
        if(matcher.matches()) {
            map.put("__" + matcher.group(1) + "_" + matcher.group(2),matcher.group(3)+"_index");
        }
    }


    /**
     * 内容替换
     * @param txt 待替换的内容
     * @param rules 替换正则表达式
     * @return 替换后的文本
     */
    public static String replaceTxt(String txt,Map<String,String> rules){
        for (String k : rules.keySet()) {
            txt=txt.replaceAll(k,rules.get(k));
        }
        return txt;
    }


    /**
     * 测试正则表达式
     * @param txt
     * @param reg
     * @return
     */
    public static boolean testReg(String txt,String reg){
        Pattern p = Pattern.compile(reg);
        Matcher matcher=p.matcher(txt);
        return matcher.matches();
    }

    /**
     * 生成文件过滤器
     * @return
     */
    public static FilenameFilter getPhpFileFilter() {
        return phpFileFilter;
    }

    /**
     * 从php文件采集function 信息
     * @return
     */
    public static Map<String,Object> phpFunctions(String path){
        Map<String,Object> funMap=new HashMap<String,Object>();
        BufferedReader br = null;

        try {
            br = new BufferedReader(new FileReader(path));
            String line="";
            String functionName = null;
            while(line!=null) {
                line = br.readLine();
                if(StringUtils.isNotEmpty(line)){
                    line = line.trim();
                    //逻辑处理
                    String name = collectEachFunctionMsg(line, functionName, funMap);
                    if(name!=null){
                        functionName = name;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(br != null) br.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return funMap;
    }

    /**
     * 从line中提取function 信息
     * @param funMap
     */
    private static String collectEachFunctionMsg(String line,String functionName,Map<String, Object> funMap) {

        if(funMap==null){
            funMap =new HashMap<String, Object>();
        }

        String name = getActionName(line);
        if(name!=null){
            functionName=name;
            //function 开始
            funMap.put(functionName,new HashMap<String,Object>());
        }

        String selectLine = getSelect(line);
        if(null!=selectLine){
            Map<String,Object> function = (Map<String, Object>) funMap.get(functionName);
            function.put("select",selectLine);
        }
        Map whereLine = getWhere(line);
        if(null!=whereLine){
            Map<String,Object> function = (Map<String, Object>) funMap.get(functionName);
            Map whereMap = (Map<String,String>) function.get("where");
            if(whereMap==null){
                whereMap=new HashMap<String,String>();
            }

            whereMap.putAll(whereLine);
            function.put("where", whereMap);
        }
        Map whereIn = getWhereIn(line);
        if(null!=whereIn){
            Map<String,Object> function = (Map<String, Object>) funMap.get(functionName);
            Map whereInMap = (Map<String,String>) function.get("where_in");
            if(whereInMap==null){
                whereInMap=whereIn;
            }else{
                whereInMap.putAll(whereIn);
            }
            function.put("where_in", whereInMap);
        }
        Map<String, String> orderByLine = getOrderBy(line);
        if(null!=orderByLine){
            Map<String,Object> function = (Map<String, Object>) funMap.get(functionName);
            Map<String, String> orderByMap = (Map<String, String>) function.get("orderBy");
            if(orderByMap==null){
                orderByMap=new HashMap<String,String>();
            }
            orderByMap.putAll(orderByLine);
            function.put("orderBy", orderByMap);
        }
        String limitLine = getLimit(line);
        if(null!=limitLine){
            Map<String,Object> function = (Map<String, Object>) funMap.get(functionName);
            function.put("limit",limitLine);
        }

        return name;
    }



}
